const express = require('express');

const routes = express.Router();

//引入mysql
const mysql = require('mysql');
//创建连接池
var pool = mysql.createPool({
    connectionLimit : 10,
    host : 'localhost',
    user : 'root',
    password : 'root',
    database : 'personmessage'
})

routes.route('/')
    .get( (req,resp)=>{

        //获取cookies
        var uid = req.cookies.uid;
        //获取cookeis的当前职务
        var port_id = req.cookies.port_id;
        var time = req.cookies.getTimes;
        var loginame = req.cookies.loginame;

        //console.log(time)
        var hous = new Date(eval(time)).getHours();
        //console.log(hous)
        var minutes = new Date(eval(time)).getMinutes();
        var seconds = new Date(eval(time)).getSeconds();
        var houss = (hous < 10) ? '0'+hous : hous;
        var minus = (minutes < 10) ? '0'+minutes : minutes;
        var secondss = (seconds < 10) ? '0'+seconds : seconds;
        var date = houss+':'+minus+':'+secondss;
        //console.log(getTime)
        var sql = `SELECT pay.* , permsg.uname , education.edu_money , station.sta_money FROM pay LEFT JOIN education ON education.id = pay.edu_id LEFT JOIN station ON station.id = pay.sta_id LEFT JOIN permsg ON permsg.uid = pay.uid WHERE pay.uid = ${uid}`;
        //console.log(sql)
        pool.getConnection(function(err,connection){
            if(err) throw err;
            //    链接成功
            connection.query(sql,(error,result)=> {

                //    释放连接   关闭数据库
                connection.release();

                //判断职务
                if(port_id == 1){
                    var port = '普通员工';

                }else if(port_id == 2){
                    var port = '行政主管';

                }else if(port_id == 3){
                    var port = '财务总监';

                }
                //获取当前时间戳  Date.now()
                var data = new Date().getTime();
                resp.render('paylist',{
                    port_id : port_id,
                    result : result,
                    port : port,
                    date : date,
                    loginame : loginame
                })
                //console.log(result)
                //sql语句出错执行报错处理
                if(error) throw error;
            })
        })
     } )
    .post( (req, resp)=>{
        var uid = req.cookies.uid;
        var month = req.query.month;
        //console.log(month)
        var sql = `UPDATE pay SET status=0 WHERE uid = ${uid} and month = ${month}`;
        //console.log(sql)
        pool.getConnection(function (err,connection){
            if(err) throw err;
            connection.query(sql,(error,result)=>{
                connection.release();//释放连接

                resp.send(result)
                //console.log(result)
                if(error) throw error;
            })
        })
    } )
//暴露接口
module.exports = routes;